package com.chenxin.wms.process.outbound.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chenxin.common.annotation.WmsLogs;
import com.chenxin.common.constant.WmsConstants;
import com.chenxin.common.core.domain.ProcResult;
import com.chenxin.common.enums.WmsBusinessStatus;
import com.chenxin.common.exception.wms.WmsException;
import com.chenxin.common.utils.StringUtils;
import com.chenxin.wms.domain.ObDetailEntity;
import com.chenxin.wms.domain.ObMasterEntity;
import com.chenxin.wms.mapper.ObDetailMapper;
import com.chenxin.wms.mapper.ObMasterMapper;
import com.chenxin.wms.process.outbound.IProcPrepareCancelByDetail;
import com.chenxin.wms.process.outbound.IProcPrepareCancelByMaster;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class ProcPrepareCancelByMaster implements IProcPrepareCancelByMaster {
    @Autowired
    private ObMasterMapper obMasterMapper;
    @Autowired
    private ObDetailMapper obDetailMapper;
    @Autowired
    private IProcPrepareCancelByDetail procPrepareCancelByDetail;

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @WmsLogs(name = "出库主单取消备货")
    public ProcResult call(Long obMasterId, Long creator) {
        if (StringUtils.isNull(obMasterId)) {
            return ProcResult.error("cancel_master_err001", "主单ID不能为空");
        }
        // 通过ID获取主单信息
        ObMasterEntity obMaster = obMasterMapper.selectById(obMasterId);
        if (obMaster == null) {
            return ProcResult.error("cancel_master_err002", "主单ID【" + obMasterId + "】不存在");
        }
        // 单据状态大于2不允许取消
        if (obMaster.getObMasterStatus() > WmsBusinessStatus.OB_MASTER_PREPARED.getCode()) {
            return ProcResult.error("cancel_master_err003", "主单当前状态【" + obMaster.getObMasterStatus() + "】无法取消");
        }
        // 根据主单ID检索明细（已成功备货或备货中）
        QueryWrapper<ObDetailEntity> obDetailQW = new QueryWrapper<>();
        obDetailQW.lambda().eq(ObDetailEntity::getObMasterId, obMasterId)
                .gt(ObDetailEntity::getObDetailStatus, WmsBusinessStatus.OB_DETAIL_INIT.getCode())
                .lt(ObDetailEntity::getObDetailStatus, WmsBusinessStatus.OB_MASTER_EXEC.getCode());
        List<ObDetailEntity> details = obDetailMapper.selectList(obDetailQW);
        if (details == null || details.size() == 0) {
            return ProcResult.error("cancel_master_err004","主单【" + obMasterId + "】无可取消的备货明细！");
        }
        // 循环处理明细
        for (ObDetailEntity detail : details) {
            try {
                ProcResult result = procPrepareCancelByDetail.call(detail.getObDetailId(), creator);
                if (!WmsConstants.PROC_SUCCESS.equals(result.getCode())) {
                    throw new WmsException("cancel_master_err005", "主单【" + obMasterId + "】取消异常，causeBy:" + result.getMessage());
                }
            } catch (WmsException e) {
                throw new WmsException("cancel_master_err005", "主单【" + obMasterId + "】取消异常，causeBy:" + e.getMessage());
            }
        }
        // 更新主单状态为初始
        obMaster.setObMasterStatus(WmsBusinessStatus.OB_DETAIL_INIT.getCode());
        obMaster.setComments("取消备货");
        obMaster.setUpdater(creator);
        obMaster.setUpdateDate(new Date());
        obMasterMapper.updateById(obMaster);

        return ProcResult.success("主单【" + obMasterId + "】取消成功！");
    }
}
